#!/bin/bash

# 运行方法 ： bash duplicate_checking.sh <number of lines> <directory>
# 关于相异行数的定义有很多种，我这里直接使用 diff -U 0 "$i" "$j" | grep -v '^---' | grep -v '^+++' | grep -c '^[+-]' 来计算。
# 相当于计算了需要修改的行数（次数）

if [ $# -ne 2 ]
then
  echo "Error: command expects only 2 arguments" >&2
	echo "try bash duplicated_checking.sh <number of lines> <directory>"
	exit 1
fi

dir=$2

if [ ! -d "$dir" ]
then
  echo "directory not found : $dir"
  exit 1
fi

if ! [[ $1 =~ ^[1-9][0-9]*$ ]]
then
  echo "the number of lines must be a positive number"
  exit 1
fi

files=$(find $dir -type f)

for i in $files
do
  for j in $files
	do
   	if [ "$i" != "$j" ] && [ "$i" \< "$j" ]
		then
			lines_x=$(diff -U 0 "$i" "$j" | grep -v '^---' | grep -v '^+++' | grep -c '^[+-]')
      lines_i=$(wc -l<"$i")
			lines_j=$(wc -l<"$j")
      if [ $lines_x -lt $1 ]
			then
      	echo "$i $j $lines_x $lines_i $lines_j"
      fi
    fi
  done
done
